package com.hackvan2012.controllers;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hackvan2012.datastore.AppDatastore;
import com.hackvan2012.datastore.dao.FoodEntryObject;
import com.hackvan2012.datastore.factory.DataFactory;

public class RequestHandler extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -677246681082441347L;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		AppDatastore appstore = new AppDatastore();
		req.setAttribute("posts", appstore.getFoodEntryListByTop(100));
		
		
		try {
			req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) {
		String params = null;
		int indexOfParams = req.getRequestURI().indexOf("/main/") + 6;
		params = req.getRequestURI().substring(indexOfParams);
		
		if (params.equals("new")) {
			try {
				req.getRequestDispatcher("/jsp/newFoodEntry.jsp").forward(req,resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (params.equals("create")) {
			AppDatastore appstore = new AppDatastore();
			String imgURL = req.getParameter("imgURL");
			String dishName = req.getParameter("dishName");
			String restaurant = req.getParameter("restaurant");
			String title = req.getParameter("title");
			String description = req.getParameter("description");
			appstore.addFoodEntry(DataFactory.createFoodEntry(imgURL, dishName, restaurant, title, description));
			try {
				resp.sendRedirect(req.getContextPath()+"/main/");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
